<template>
  <div class="app-container">
    <el-form :inline="true" :model="params" class="demo-form-inline">
      <el-form-item label="任务阶段">
        <el-select 
          v-model="params.queryStageType"
          filterable
          @change="queryCaseByAcademicYearRemote"
          >
          <el-option
            v-for="item in queryStageType"
            :key="item.typeDesc"
            :label="item.typeDesc"
            :value="item.typeCode">
          </el-option>
        </el-select>
        <el-select 
          v-show="params.queryStageType!=0"
          v-model="params.queryStageAcyeId" clearable
          remote
          reserve-keyword
          placeholder="请选择学年"
          @change="queryCaseByAcademicYearRemote"
          :remote-method="queryCaseByAcademicYearRemote">
          <el-option
            v-for="item in queryCaseByAcyeSelect"
            :key="item.value"
            :label="item.acyeBeginYear + '~' + item.acyeEndYear + '学年'"
            :value="item.id">
          </el-option>
        </el-select>
        <el-select 
          v-show="params.queryStageType==2"
          v-model="params.queryStageTetiId" clearable
          remote
          reserve-keyword
          placeholder="请选择学期"
          :remote-method="queryCaseByTermtimeRemote">
          <el-option
            v-for="item in queryCaseBytermTimeList"
            :key="item.value"
            :label="'第' + item.tetiTerm + '学期'"
            :value="item.id">
          </el-option>
        </el-select>

        <el-select 
          v-show="params.queryStageType==3"
          v-model="params.queryStageMonth"
          clearable
          remote
          reserve-keyword
          placeholder="请选择月份"
          :remote-method="queryCaseByMonthRemote">
          <el-option
            v-for="item in queryCaseByMonthList"
            :key="item.value"
            :label="Math.floor(item.yearMonth/100) + '年' + item.yearMonth%100 + '月'"
            :value="item.yearMonth">
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="考核名称">
        <el-input v-model="params.taskName" placeholder="请输入考核名称"></el-input>
      </el-form-item>
      <el-form-item label="受评人">
        <el-select v-model="params.tetaCoverUserId" filterable remote reserve-keyword clearable placeholder="请输入关用户名"
          :remote-method="queryCaseByTetaCoverUserRemote">
          <el-option v-for="item in queryCaseByTetaCoverUser" :key="item.id" :label="item.userName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>
    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" v-hasPermi="['teacher:evaluation:task:add']"
          @click="handerAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple"
          v-hasPermi="['teacher:evaluation:task:remove']" @click="handleDelete">删除
        </el-button>
      </el-col>
    </el-row> -->

    <el-table :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index"/>
      <el-table-column label="考核名称" align="center" prop="tetaName" />
      <el-table-column label="考核阶段" align="center" prop="tetaStageType">
        <template slot-scope="scope">
          <span v-if="scope.row.tetaStageType==1">
            {{scope.row.acyeBeginYear + '~' + scope.row.acyeEndYear }}学年
          </span>
          <span v-if="scope.row.tetaStageType==2">
            {{scope.row.tetiBeginYear + '~' + scope.row.tetiEndYear }}学年 第{{scope.row.tetiTerm}}学期
          </span>
          <span v-if="scope.row.tetaStageType==3">
            {{scope.row.tetaMonth}}月份
          </span>
        </template>

      </el-table-column>
      <el-table-column label="考核方案名称" align="center" prop="tescName" :show-overflow-tooltip="true"/>
      <el-table-column label="考核方案类别" align="center" prop="tescType" :show-overflow-tooltip="true">
        <template slot-scope="scope">
            <span v-if="scope.row.tetaType == 0">
                班主任考核
            </span>
            <span v-else-if="scope.row.tetaType == 1">
                教职工考核
            </span>
        </template>
      </el-table-column>
      <el-table-column label="考核人(受评人)" align="center" prop="tetaCoverUserName" />
      <el-table-column label="考核结果" align="center" prop="tetaCoverUserName">
        <template slot-scope="scope">
          {{scope.row.tereShowType==2? scope.row.tereShowResultLevel : scope.row.tereShowResultScore}}
        </template>
      
      </el-table-column>
      <!-- <el-table-column label="考核状态" align="center" prop="tetaStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.tetaStatus==0">进行中</span>
          <span v-if="scope.row.tetaStatus==1">结束</span>
        </template>
      </el-table-column> -->
      <el-table-column label="生成时间" align="center" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="修改时间" align="center" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyTime) }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" circle type="success" icon="el-icon-edit" v-hasPermi="['system:termtime:edit']"
            @click="handleUpdate(scope.row)" />
          <el-button size="mini" circle type="danger" icon="el-icon-delete" v-hasPermi="['system:termtime:remove']"
            @click="handleDelete(scope.row)" />
        </template>
      </el-table-column> -->
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="params.pageNum" :limit.sync="params.pageSize"
      @pagination="getList" />

    <!-- 新增对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="570px">
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
         <el-form-item label="任务名称" prop="tetaName">
          <el-input v-model="form.tetaName" placeholder="请输入任务名称"></el-input>
        </el-form-item>
        
        <el-form-item label="考核方案"  prop="tescId"> 
          <el-radio-group v-model="form.tetaType" size="medium" @change="addOrUpdateCaseBySchemeRemote" :disabled="form.id">
            <div>
              <span  v-for="(item, typeCode) in queryEvscType" :key="typeCode" style="padding-right:20px;">
                <el-radio v-if="item.typeCode!=-1" :key="typeCode" :label="item.typeCode">{{item.typeDesc}}</el-radio>       
              </span>
            </div>
          </el-radio-group>
          <div>
            <el-select v-model="form.tescId" placeholder="请选择考评方案" :disabled="form.id">
              <span v-for="item in schemeList" :key="item.id">
                <el-option :label="item.tescName" :value="item.id" v-if="form.tetaType == -1 || item.tescType == form.tetaType">
                </el-option>
              </span>
            </el-select>
          </div>
        </el-form-item>
        <el-row type="flex" align="top">
          <el-col>
            <el-form-item label="考评阶段" prop="tetaStageType">
              <el-radio-group v-model="form.tetaStageType" size="medium" @change="addOrUpdateCaseByAcademicYearRemote">
                <span  v-for="(item, typeCode) in queryStageType" :key="typeCode" style="padding-right:20px;">
                  <el-radio  v-if="item.typeCode!=0" :key="typeCode" :label="item.typeCode" :disabled="form.id"
                  >{{item.typeDesc}}</el-radio>
                </span>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="acyeId">
                <el-select 
                v-show="form.tetaStageType!=0"
                v-model="form.acyeId"
                remote
                reserve-keyword
                placeholder="请选择学年"
                @change="addOrUpdateCaseByAcademicYearRemote"
                :remote-method="addOrUpdateCaseByAcademicYearRemote"
                :disabled="form.id">
                <el-option
                  v-for="item in addOrUpdateCaseByAcyeSelect"
                  :key="item.value"
                  :label="item.acyeBeginYear + '~' + item.acyeEndYear + '学年'"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="tetiId">
              <el-select 
                v-show="form.tetaStageType==2"
                v-model="form.tetiId"
                remote
                reserve-keyword
                placeholder="请选择学期"
                :remote-method="addOrUpdateCaseByTermtimeRemote"
                :disabled="form.id">
                <el-option
                  v-for="item in addOrUpdateCaseBytermTimeList"
                  :key="item.value"
                  :label="'第' + item.tetiTerm + '学期'"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="tetaMonth" style="margin-top:-22px;">
              <el-select 
                :disabled="form.id"
                v-show="form.tetaStageType==3"
                v-model="form.tetaMonth"
                remote
                reserve-keyword
                placeholder="请选择月份"
                :remote-method="addOrUpdateCaseByMonthRemote">
                <el-option
                  v-for="item in addOrUpdateCaseByMonthList"
                  :key="item.yearMonth"
                  :label="Math.floor(item.yearMonth/100) + '年' + (item.yearMonth % 100) + '月'"
                  :value="item.yearMonth">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="受评人" prop="tetaCoverUserId">
          <el-select v-model="form.tetaCoverUserId" filterable remote reserve-keyword placeholder="请输入关键词" :disabled="form.id"
            :remote-method="onRemoteMethod" >
            <el-option v-for="item in listrole" :key="item.id" :label="item.userName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="打分人" prop="taskScoreUserIds">
          <el-row style="pading:10px 0 10px 0;border:1px solid #dfe6ec;" type="flex" align="middle" @click.native="onGrade">
            <el-col>
              <el-tag style="margin:0 5px 0 5px;" v-for="item in taskScoreUserlist" :key="item.id">{{item.userName}}</el-tag>
              <el-input v-model="form.taskScoreUserIds" type="hidden"/>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="考评分参与者是否可见">
          <el-radio v-model="form.tetaUserIsVisit" :label="1">可见</el-radio>
          <el-radio v-model="form.tetaUserIsVisit" :label="0">不可见</el-radio>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit(amend)">确 定</el-button>
        <el-button @click="open=false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 打分人展示框 -->
    <el-dialog title="选择打分人" :visible.sync="grade">
      <!-- 已选打分人 -->
      <el-row style="border:1px solid #dfe6ec">
          <div style="margin:10px 0px 10px 10px;">已选打分人：</div>
          <div style="margin:10px 0px 30px 10px;">
            <el-tag style="margin-right:10px;"
            v-for="tag in taskScoreUserlist"
            :key="tag.id"
            closable
            @close="handleTagScoreClose(tag)"
            >
            {{tag.userName}}
          </el-tag>
          </div>
      </el-row>
      <el-row style="margin:10px 5px 5px 0; padding:20px;border:1px solid #dfe6ec"  type="flex" align="middle">
        <el-col :span="8">
            <el-row type="flex" align="middle">
              <el-col :span="6">归属部门</el-col> 
              <el-col>
                <el-select v-model="params.sydeName" placeholder="请选择" @change="onRemoteMethod(params,1)">
                  <el-option v-for="item in deptList" :key="item.id" :label="item.label" :value="item.label">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
        </el-col>
        <el-col :span="8">
            <el-row  type="flex" justify="space-around" align="middle">
              <el-col :span="6">姓     名</el-col>
              <el-col>
                <el-input placeholder="请输入姓名" style="width:150px"
                  v-model="params.userName" clearable size="small">
                </el-input>
              </el-col>
            </el-row>
        </el-col>
        <el-col :span="8" >
          <div style="float:right"><el-button type="primary">查询</el-button></div>
        </el-col>
      </el-row>
      <div style=" border:1px solid #dfe6ec; margin: 5px 0 10px 0">
        <el-table
          style="width:100%;"
          ref="scoreUserTable"
          :row-key="getRowKeys"
          :data="scoreUserList"
          tooltip-effect="dark"
          @selection-change="handleSoreTableSelectionChange"
          row-class-name="score-el-table__row">
          <el-table-column type="selection"  style="width:20%" :reserve-selection="true"/>
          <el-table-column  label="序号" type="index"/>
          <el-table-column  label="用户姓名" style="width:40%">
            <template slot-scope="scope">{{ scope.row.userName}}</template>
          </el-table-column>
          <el-table-column label="所属部门" style="width:40%">
            <template slot-scope="scope">{{ scope.row.sydeName}}</template>
          </el-table-column>
        </el-table>
        <pagination style="margin:0 0 20px 0" v-show="scoreUserTotal > 0" :total="scoreUserTotal" :page.sync="paramsScoreUser.pageNum" :limit.sync="paramsScoreUser.pageSize"
        @pagination="getScoreUserList" />
      </div>
      <el-row type="flex" justify="center" align="middle" style="margin-top:20px;">
        <el-button @click="grade = false,open=true">取 消</el-button>
        <el-button type="primary" @click="submit(peoplewho)">确 定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { listEvItem, createEvItem, del, infoByTask, update, userEvItem, 
  academicYearEvItem, academicTermtimeEvItem, academicMonthEvItem
} from "@/api/teacher/evaluation/task_result.js";
import { list } from "@/api/teacher/evaluation/scheme.js";
import { treeselect } from "@/api/system/dept";
import { listTermtime } from "@/api/system/termtime.js";
export default {
  data() {
    //  ================ 自定义校验 ==============
    // 考评阶段 - 学期
    var validTetiId = (rule, value, callback) => {
        //console.log("tetiId", rule);
        if (this.form.tetaStageType == 2 &&  (value == '' || value == undefined )) {
          callback(new Error(rule.message));
        } else {
          this.$refs.form.clearValidate(rule.field);
          callback();
        }
    };
     // 考评阶段 - 月份
    var validTetaMonth = (rule, value, callback) => {
        // console.log("month", rule);
        if (this.form.tetaStageType == 3 && (value == '' || value == undefined )) {
          callback(new Error(rule.message));
        } else {
          this.$refs.form.clearValidate(rule.field);
          callback();
        }
    };
    // 打分人校验
    var validTaskScoreUserIds = (rule, value, callback) => {
        // console.log("validTaskScoreUserIds", rule);
        if (this.form.taskScoreUserIds == '' || this.form.taskScoreUserIds == undefined) {
          callback(new Error(rule.message));
        } else {
          this.$refs.form.clearValidate(rule.field);
          callback();
        }
    };
    return {
      // 阶段类型
      queryStageType:[ // 查询列表是的条件
        {typeCode:0, typeDesc: "全部"},
        {typeCode:1, typeDesc: "学年"},
        {typeCode:2, typeDesc: "学期"},
        {typeCode:3, typeDesc: "月份"}
        ],
       // 方案类型
      queryEvscType:[
        {typeCode:-1, typeDesc: "全部"},
        {typeCode:0, typeDesc: "班主任"},
        {typeCode:1, typeDesc: "教职工"}
        ],
      queryCaseByTetaCoverUser:[], // 受评人（下拉展示数据）
      queryCaseByTetaCoverUserParams:{ // 受评人（查询参数）
        userName: '',
        pageNum: 1,
        pageSize: 50
      },
      queryCaseByAcyeSelect:[], // 学年select数据
      queryCaseBytermTimeList: [], // 学年学期下拉数据
      queryCaseByMonthList: [], // 学年月份下拉数据
      
      //列表显示
      params: { // 查询条件的值
        pageNum: 1,
        pageSize: 10,
        tetaCoverUserId: '', // 受评人ID
        queryStageType: 0, // 查询阶段类型
        queryStageAcyeId: undefined, // 查询阶段：学年ID
        queryStageTetiId: undefined, // 查询阶段：学期ID
        queryStageMonth: undefined, // 查询阶段： 月份 （yyyyMM）
      },
      taskList: [],
     

      // 添加或编辑时
      addOrUpdateCaseByAcyeSelect:[], // 学年select数据
      addOrUpdateCaseBytermTimeList: [], // 学年学期下拉数据
      addOrUpdateCaseByMonthList: [], // 学年月份下拉数据






      //受评人保存数组
      listrole: [],
      //多选框选中数据id
      ids: [],
      //打分人数组
      scoreUserList: [],
      tempAddScoreUserList: [],
      //考评方案选择
      schemeList: [],
      //部门数组
      deptList: [],
      //打分人暂存数组
      taskScoreUserlist: [],


      //任务发起人
      initiator: '',
      //新增对话框
      open: false,
      //删除按钮禁用状态
      multiple: true,
      //总条数
      total: 0,
      scoreUserTotal: 0,
      //打分人对话框
      grade: false,
      title: "",
      //修改和添加方法提交判断条件
      amend: "",
      peoplewho: "打分人",

      //新增表单参数
      form: {
      },

      // 打分人查询参数
      paramsScoreUser:{
        pageNum: 1,
        pageSize: 10,
      },
      //表单校验
      rules: {
        tetaName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        tescId: [
          { required: true, message: "请选择方案", trigger: "change" }
        ],
        tetaStageType: [
          {required: true, message: "", trigger: "change" }
        ],
        acyeId: [
          {required: true, message: "请选择学年", trigger: "change" }
        ],
        tetiId: [
          {message: "请选择学年学期", validator: validTetiId, trigger: "change" }
        ],
        validTetaMonth: [
          {message: "请选择学年月份", validator: validTetiId, trigger: "change" }
        ],
        tetaCoverUserId: [
          {required: true, message: "请选择受评人", trigger: "change" }
        ],
        taskScoreUserIds: [
          {message: "请选择打分人", validator: validTaskScoreUserIds, trigger: "change" }
        ],
      }
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getList();
    
    // 查询条件：受评人加载
    this.queryCaseByTetaCoverUserRemote(this.queryCaseByTetaCoverUserParams.userName);

    //受评人加载方法
    this.onRemoteMethod();
    //打分人加载方法
    this.getScoreUserList();
    //部门方法
    var dePartparams = {
      pageNum: 1,
      pageSize: 10,
    }
    treeselect(dePartparams).then(res => {
      this.deptList = res.data[0].children;
    })
  },
  methods: {
    /** 工作考评列表 */
    getList() {
      listEvItem(this.params).then(res => {
        this.taskList = res.data.list;
        this.total = res.data.total;
      })
    },

    getScoreUserList() {
      userEvItem(this.paramsScoreUser).then(res => {
        this.scoreUserList = res.data.list;
        this.scoreUserTotal = res.data.total;
        this.refreshTableScoreCheck();
      })
    },
    // 刷新分数据（分页重新加载数据时使用，tag标签中的数据进行自动选中的数据（,根据最终存储情况清除掉））
    refreshTableScoreCheck(){
      // var tempScorePageRowsObj = Array.from(this.$refs.scoreUserTable.$el.getElementsByClassName('el-table__row'));
      var notExistList = [];
      if(this.grade) {
        for (var i=0, size = this.$refs.scoreUserTable.selection.length; i<size; i++) {
          //console.log("refreshTableScoreCheck", this.$refs.scoreUserTable.selection[i].id);
          var exist = false;
          for (var j=0, jSize = this.taskScoreUserlist.length; j <jSize; j++) {
            //console.log(this.$refs.scoreUserTable.selection[i].id, this.taskScoreUserlist[j].id);
            if (this.$refs.scoreUserTable.selection[i].id == this.taskScoreUserlist[j].id) {
              exist = true;
              break;
            }
          }
          if (!exist) {
            notExistList.push(this.$refs.scoreUserTable.selection[i]);
          }
       }
       for (var i=0, iSize = notExistList.length; i<iSize; i++) {
          this.$refs.scoreUserTable.toggleRowSelection(notExistList[i], false);
       }
      }
    }
    ,
    getRowKeys(row) {
      return  row.id;
    },
    //清空方法
    handerAdd() {
      this.form = {
        id: undefined,
        tetaStageType: 1,     // 考评阶段 form.tetaStageType
        acyeId: undefined,    // 考评阶段 - 学年id form.acyeId
        tetiId: undefined,    // 考评阶段 - 学期id form.tetiId
        tetaMonth: undefined, // 考评阶段 - 学年月份 form.tetaMonth

        tetaType: 0,          // 方案类型 form.tetaType
        tescId: undefined,    // 方案类型 - 考评方案id

        tetaCoverUserId: null,// 目标人群 - 受评人id
        taskScoreUserIds: "", // 目标人群 - 打分人
        tetaUserIsVisit: 0,   // 目标人群 - 打分人评份情况，是否相互可见
        tetaName: "",         // 任务 - 名称
        tetaStatus: undefined,// 任务 - 状态
        userId: undefined,    // 任务 - 发者id
        remarks: ""           // 备注
      }
      this.taskScoreUserlist = [];
      
      this.addOrUpdateCaseByAcademicYearRemote();
        //考评方案
      this.addOrUpdateCaseBySchemeRemote();

      this.title='添加任务',
      this.open=true;
      this.$refs.form.clearValidate();
    },

    //多选框选中数据方法
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.multiple = !selection.length;
    },

    //打分人：table列表多选框选中数据方法
    handleSoreTableSelectionChange(selection) {
      // 当前选择的用户
      this.tempAddScoreUserList = selection;
      //console.log("this.taskScoreUserlist", this.taskScoreUserlist);
      //console.log("this.tempAddScoreUserList", this.tempAddScoreUserList);
      //1、 把表格中选中的数据 =》 设置到tag中【追加】
      let notExistList=[];
      for (let i=0, iSize = this.tempAddScoreUserList.length; i<iSize; i++) {
        var exist = false;
        for (let j=0, jSize = this.taskScoreUserlist.length; j < jSize; j++) {
          if (this.tempAddScoreUserList[i].id == this.taskScoreUserlist[j].id) {
            exist =true;
            break;
          }
        }
        if (!exist) {
          notExistList.push(this.tempAddScoreUserList[i]);
        }
      }
      this.taskScoreUserlist.push(...notExistList);
      //console.log("this.taskScoreUserlist", this.taskScoreUserlist);

       //2、 把表格中选中没有选中的数据，从tag中【移除】
      // var tempScorePageRowsObj = Array.from(this.$refs.scoreUserTable.$el.getElementsByClassName('score-el-table__row')); 获取dom对象（这里没有用到）
      let notSelectList=[];
      for (let i=0, iSize = this.scoreUserList.length; i<iSize; i++) {
        //console.log("scoreUserList.name", this.scoreUserList[i].userName," this.scoreUserList[i].id", this.scoreUserList[i].id )
        var exist = false;
        for (let j=0, jSize = this.tempAddScoreUserList.length; j < jSize; j++) {
          //console.log("tempAddScoreUserList[j].userName", this.tempAddScoreUserList[j].userName," this.tempAddScoreUserList[j].id", this.tempAddScoreUserList[j].id);
          if (this.scoreUserList[i].id == this.tempAddScoreUserList[j].id) {
            exist =true;
            break;
          }
        }
        if (!exist) {
          notSelectList.push(this.scoreUserList[i]);
        }
      }
      //console.log("notSelectList.size:", notSelectList.length );

      let needRemoveTagList=[];
      for (var i=0, isize=notSelectList.length; i<isize; i++) {
          // tag 标签移除
          for (var j=0, jsize = this.taskScoreUserlist.length; j<jsize; j++) {
            if (notSelectList[i].id == this.taskScoreUserlist[j].id) {
              needRemoveTagList.push(this.taskScoreUserlist[j]);
            }
          }
      }
      //console.log("remove tag score user size:", needRemoveTagList.length );
      for(var i=0, isize = needRemoveTagList.length; i<isize; i++) {
         // tag 标签移除
         this.handleTagScoreClose(needRemoveTagList[i]);
      }
    },
  
    // 打分人：把当前确认选择的打分人，删除单个的方法
    handleTagScoreClose(tag) {
      var canelSelectRow = undefined;
      for (var i=0, size= this.$refs.scoreUserTable.selection.length; i<size; i++) {
          // console.log("handleTagScoreClose",tag, this.$refs.scoreUserTable.selection[i]);
          if (tag.id == this.$refs.scoreUserTable.selection[i].id) {
            canelSelectRow = this.$refs.scoreUserTable.selection[i];
          }
      }
      if (canelSelectRow != undefined) {
        this.$refs.scoreUserTable.toggleRowSelection(canelSelectRow, false);
      }
      // tag 标签移除
      let index = this.taskScoreUserlist.indexOf(tag); // 标签索引
      this.taskScoreUserlist.splice(index, 1); // 移除标签

      this.taskScoreUserIdsRefresh();
    }
    ,
    //打分人数据控制方法
    onGrade() {
      if(this.form.id){
          return;
      }
      this.open = false;
      this.grade = true;
      this.getScoreUserList(this.paramsScoreUser);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.params.pageNum = 1;
      this.getList();
    },
    //提交方法
    submit(amend) {
      if (amend == '修改') {
        this.$refs["form"].validate(valid => {
          if (valid) {
          update(this.form.id, this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            } else {
              this.msgError(response.message);
            }
          });
        }});
      } else if (amend == "打分人") {
        this.grade = false;
        this.open = true;
        this.taskScoreUserIdsRefresh();
       
      } else {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.$loading = true;
            createEvItem(this.form).then(res => {
              this.$loading = false;
              if (res.code === 200) {
                this.msgSuccess("新增成功");
                this.form = res;
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          }});
      }
      this.amend = "";
    },
    //删除任务方法
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除任务编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return del(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function () { });
    },
    //获取修改任务信息
    handleUpdate(row) {
      //console.log("handleUpdate", row);
      this.amend = "修改";
      this.title = "修改任务"
      this.form.id=row.id;
      // task打分人（已存储）
      this.taskScoreUserlist = [];
      //考评方案
      this.addOrUpdateCaseBySchemeRemote();
      infoByTask(row.id).then(res => {
        //console.log(res, 'res获取修改任务信息')
        this.form = res.data;
        this.taskScoreUserlist = res.data.scoreUserList;
        this.form.tetaCoverUserId=res.data.tetaCoverUserId;
        this.listrole = [res.data.tetaCoverUser]
        this.taskScoreUserIdsRefresh();
        // 学年
        this.addOrUpdateCaseByAcademicYearRemote();  
        this.open = true;
        this.$refs.form.clearValidate();
      })
     
    },
    //受评人和打分人加载方法
    onRemoteMethod(query, id) {
      var params = {
        pageNum: 1,
        pageSize: 50,
      }
      if (id == 1) {
        if (query.userName != null && query.sydeName != null) {
          // params.userName = query.userName;
          // params.sydeName = query.sydeName;
          userEvItem(params).then(res => {
            this.listGrade = res.data.list
          })
        }
      } else {
        params.userName = query;
        userEvItem(params).then(res => {
          this.listrole = res.data.list;
        })
      }
    },
    taskScoreUserIdsRefresh() {
        console.log("taskScoreUserIdsRefresh");
        this.form.taskScoreUserIds = "";
        console.log("taskScoreUserIdsRefresh：this.form.taskScoreUserlist", this.form.taskScoreUserlist);
        for(var i=0, iSize=this.taskScoreUserlist.length; i < iSize; i++) {
            console.log("this.taskScoreUserlist:", this.taskScoreUserlist);
            this.form.taskScoreUserIds += this.taskScoreUserlist[i].id + ",";
        }
        if (this.form.taskScoreUserIds !="") {
          this.form.taskScoreUserIds = this.form.taskScoreUserIds.substring(0, this.form.taskScoreUserIds.lastIndexOf(","));
        }
        
    }
    ,
    // 查询条件（受评人）下拉框
    queryCaseByTetaCoverUserRemote(query) {
      this.queryCaseByTetaCoverUserParams.userName = query;
      userEvItem(this.queryCaseByTetaCoverUserParams).then(res => {
        this.queryCaseByTetaCoverUser = res.data.list;
      })
    },
    // 查询条件（学年）下拉框
    queryCaseByAcademicYearRemote() {
      if (this.params.queryStageType == 0) {
        return;
      }
      this.queryCaseBytermTimeList = []
      this.queryCaseByMonthList = []
      this.params.queryStageMonth = undefined;
      this.params.queryStageTetiId = undefined;
      
      academicYearEvItem().then(res => {
        this.queryCaseByAcyeSelect = res.data;
        if (this.queryCaseByAcyeSelect && this.queryCaseByAcyeSelect.length != 0) {
          let currentAcye = this.queryCaseByAcyeSelect.filter(item => item.current == true);
          if (this.params.queryStageAcyeId == undefined && currentAcye && currentAcye.length != 0) {
            this.params.queryStageAcyeId = currentAcye[0].id;
          }
          // 阶段类型为学期时
          if(this.params.queryStageType == 2) {
            this.queryCaseByTermtimeRemote();
          }
          // 阶段类型为月份时
          if(this.params.queryStageType == 3) {
            this.queryCaseByMonthRemote();
          }
        } else {
          this.params.queryStageAcyeId = undefined;
        }
      })
    },
    // 查询条件（学年学期）下拉框
    queryCaseByTermtimeRemote() {
      if (this.params.queryStageType == 2 && this.params.queryStageAcyeId) {
        academicTermtimeEvItem(this.params.queryStageAcyeId).then(res => {
        this.queryCaseBytermTimeList = res.data;
        if (this.queryCaseBytermTimeList && this.queryCaseBytermTimeList.length > 0) {
          let currentTermTime = this.queryCaseBytermTimeList.filter(item => item.current == true);
          if (this.params.queryStageTetiId == undefined && currentTermTime && currentTermTime.length != 0) {
            this.params.queryStageTetiId = currentTermTime[0].id;
          }
        } else {
          this.params.queryStageTetiId = undefined;
        }
      })
      } else {
        this.queryCaseBytermTimeList = []
      }
    },
    // 查询条件（学年月份）下拉框
    queryCaseByMonthRemote() {
      if (this.params.queryStageType == 3 && this.params.queryStageAcyeId) {
        academicMonthEvItem(this.params.queryStageAcyeId).then(res => {
        this.queryCaseByMonthList = res.data;
        if (this.queryCaseByMonthList && this.queryCaseByMonthList.length > 0) {
          let currentMonthTime = this.queryCaseByMonthList.filter(item => item.current == true);
          if (this.params.queryStageMonth == undefined && currentMonthTime && currentMonthTime.length != 0) {
            this.params.queryStageMonth = currentMonthTime[0].yearMonth;
          }
        } else {
            this.params.queryStageMonth = undefined
        } 
      })
      } else {
        this.queryCaseByMonthList = []
      }
    },
    // 方案下拉选择
    addOrUpdateCaseBySchemeRemote() {
      let schemeQueryParams = {
        pageNum: 1,
        pageSize: 50,
      };
      this.form.tescId = undefined;
      list(schemeQueryParams).then(res => {
        this.schemeList = res.data.list;
      })
    },

    // 编辑或修改 条件（学年）下拉框
    addOrUpdateCaseByAcademicYearRemote() {
      this.addOrUpdateCaseBytermTimeList = [];
      this.addOrUpdateCaseByMonthList = [];
      if (!this.form.id) {
          this.form.tetaMonth = undefined
          this.form.tetiId = undefined
      }
      academicYearEvItem().then(res => {
        this.addOrUpdateCaseByAcyeSelect = res.data;
        if (this.addOrUpdateCaseByAcyeSelect && this.addOrUpdateCaseByAcyeSelect.length != 0) {
          let currentAcye = this.addOrUpdateCaseByAcyeSelect.filter(item => item.current == true);
          if (this.form.acyeId == undefined && currentAcye && currentAcye.length != 0) {
            this.form.acyeId = currentAcye[0].id;
          }

          // 根据不同的类型，去除掉对应的错误校验提示
          if (this.form.tetaStageType == 2) {
            // console.log("this.$refs.form.clearValidate(tetaMonth)");
            this.$refs.form.clearValidate("tetaMonth");
          } else if(this.form.tetaStageType == 3) {
            // console.log("this.$refs.form.clearValidate(tetiId)");
            this.$refs.form.clearValidate("tetiId");
          } else {
            this.$refs.form.clearValidate("tetaMonth");
            this.$refs.form.clearValidate("tetiId");
          }

          // 阶段类型为学期时
          if(this.form.tetaStageType == 2 && this.form.acyeId != undefined) {
            this.addOrUpdateCaseByTermtimeRemote();
          }
          // 阶段类型为月份时
          if(this.form.tetaStageType == 3 && this.form.acyeId != undefined) {
            this.addOrUpdateCaseByMonthRemote();
          }
        }     
      })
    },
    // 编辑或修改 查询条件（学年学期）下拉框
    addOrUpdateCaseByTermtimeRemote() {
      if (this.form.tetaStageType == 2 && this.form.acyeId != undefined) {
        academicTermtimeEvItem(this.form.acyeId).then(res => {
        this.addOrUpdateCaseBytermTimeList = res.data;
        if (this.addOrUpdateCaseBytermTimeList && this.addOrUpdateCaseBytermTimeList.length > 0) {
          let currentTermTime = this.addOrUpdateCaseBytermTimeList.filter(item => item.current == true);
          if (this.form.tetiId == undefined && currentTermTime && currentTermTime.length != 0) {
            this.form.tetiId = currentTermTime[0].id;
          }
        } else {
          this.form.tetiId = undefined;
        }

      })
      }
    },
    // 编辑或修改 查询条件（学年月份）下拉框
    addOrUpdateCaseByMonthRemote() {
      if (this.form.tetaStageType == 3 && this.form.acyeId != undefined) {
        academicMonthEvItem(this.form.acyeId).then(res => {
        this.addOrUpdateCaseByMonthList = res.data;
        if (this.addOrUpdateCaseByMonthList && this.addOrUpdateCaseByMonthList.length > 0) {
          let currentMonthTime = this.addOrUpdateCaseByMonthList.filter(item => item.current == true);
          if ( this.form.tetaMonth == undefined && currentMonthTime && currentMonthTime.length != 0) {
            this.form.tetaMonth = currentMonthTime[0].yearMonth;
          }
        } else {
          this.form.tetaMonth = undefined;
        }
      })
      }
    }
  },
  // 监控data中的数据变化
  watch: {
    show: function (val) {
      if (!val) {
        this.$data.selectApp = "";
      }
    }
  }
};
</script>